/***************************************************************************
 *   Copyright (C) 2009 by Zheng Yonglei
 *   zhengyonglei@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "LoginDialog.h"
#include "Logger.h"

LoginDialog::LoginDialog(QDialog *parent)
    : QDialog(parent)
{
	ui.setupUi(this);

	setWindowFlags(Qt::WindowStaysOnTopHint);
	QObject::connect(ui.closeButton, SIGNAL(clicked()), this, SLOT(accept()));
	QObject::connect(ui.newAccountButton, SIGNAL(clicked()), this, SLOT(newUser()));
	QObject::connect(ui.deleteAccountButton, SIGNAL(clicked()), this, SLOT(deleteUser()));
	QObject::connect(ui.usrList, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(accountSelected(QListWidgetItem*)));
	QObject::connect(ui.loginButton, SIGNAL(clicked()), this, SLOT(login()));
	QObject::connect(ui.dictButton, SIGNAL(clicked()), this, SLOT(dictMode()));
	QObject::connect(this, SIGNAL(itemActivated(QListWidgetItem*)), ui.usrList, SIGNAL(itemActivated(QListWidgetItem*)));

	QShortcut* closeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape),  this);
	QObject::connect(closeShortcut,SIGNAL(activated()),this,SLOT(accept()));

	setAccountTable();
}

LoginDialog::~LoginDialog()
{

}

void LoginDialog::setAccountTable()
{
	ui.usrList->clear();
	mUserList.clear();
	QDir dir = QDir::current();
	dir.cd(USER_DIR);
	QStringList files = dir.entryList(QStringList() ,QDir::Dirs);
	for (int i=0; i<files.size(); i++)
	{
		if (files[i]!=QString("..") && files[i]!=QString("."))
		{
			LOG<<"File["<<i<<"]="<<files[i].toUtf8().data()<<endl;
			QString usr = files[i];
			mUserList<<usr;
			ui.usrList->addItem(usr);
		}
	}

	if (!OPT.lastAccount.isEmpty())
	{
		QList<QListWidgetItem*> usrs = ui.usrList->findItems(OPT.lastAccount, Qt::MatchExactly);
		if (usrs.isEmpty())
		{
			LOG<<"Invalid OPT.lastAccount: "<<OPT.lastAccount.toUtf8().data()<<endl;
			OPT.lastAccount.clear();
		}
		else
		{
			ui.usrNameEdit->setText(OPT.lastAccount);
			usrs[0]->setSelected(true);
			emit itemActivated(usrs[0]);
		}
	}
}

void LoginDialog::login()
{
	QString usrPath(USER_DIR);
	//QString comFilePath = "./data/common/";
	mCurUser = ui.usrNameEdit->text();
	bool findUsr = false;
	for (int i=0; i<mUserList.size(); i++)
		if (mUserList[i] == mCurUser)
			findUsr = true;

	if (!findUsr)
	{
		QString message="Please select a VALID account and login.";
		MessageBox::showWarning(QMessageBox::Warning,QString("Warning!"),message,12,this);
		return;
	}

	if (!DB.curUsr.isEmpty())
		DB.closeDB(DB.curUsr);

	OPT.lastAccount = mCurUser;
	DB.curUsr = mCurUser;
	usrPath = usrPath + mCurUser + "/" + mCurUser + ".db";
	if (!DB.openDB(usrPath, mCurUser))
		assert(0);

	OPT.hasLogined = true;
	this->done(LT_Success);
}

void LoginDialog::accountSelected(QListWidgetItem* item)
{
	QString selectedUsr = item->text();
	OPT.lastAccount = selectedUsr;
	ui.usrNameEdit->setText(selectedUsr);
}

void LoginDialog::newUser()
{
	QString newUsrName = ui.usrNameEdit->text();
	QString usrDBDir(USER_DIR);
	if (mUserList.contains(newUsrName))
	{
		QString message="This user already exists.";
		MessageBox::showWarning(QMessageBox::Warning,QString("Warning!"),message,12,this);
		return;
	}

	newUsrName = newUsrName.simplified();
	if (newUsrName.isEmpty())
	{
		QString message="Name is empty ! ";
		MessageBox::showWarning(QMessageBox::Warning,QString("Warning!"),message,12,this);
		return;
	}

	QDir curDir = QDir::current();
	curDir.mkdir(usrDBDir + newUsrName);
	QString oldFile = usrDBDir + QString("new.db");
	QString newFile = usrDBDir + newUsrName+"/"+newUsrName+".db";
	if (!QFile::copy(oldFile, newFile))
	{
		LOG<<"Fail to copy file."<<endl;
		assert(0);
	}

	OPT.lastAccount = newUsrName;
	setAccountTable();

	SQLiteDB db;
	if (!db.openDB(newFile, newUsrName))
		assert(0);

	QString command;
	QTextStream cs(&command);
	cs<<"update usr set usr_name='"<<newUsrName<<"';";
	db.execQuery(command, QueryT_Write, newUsrName);
}

void LoginDialog::deleteUser()
{
	QString usrToDelete = ui.usrNameEdit->text();
	QString message=QString("Are you sure to delete user '%1'?").arg(usrToDelete);
	if (MessageBox::showConfirm(QMessageBox::Warning,QString("Warning!"),message,12,this) == 0x00004000) //QMessageBox::Yes
	{
		if (usrToDelete == OPT.lastAccount)
		{
			OPT.lastAccount.clear();
		}

		QDir curDir = QDir::current();
		//delete user
		QDir dir = QDir::current();
		dir.cd(USER_DIR);
		dir.cd(usrToDelete);
		QStringList files = dir.entryList(QStringList());
		for (int i=0; i<files.size(); i++)
			dir.remove(files[i]);

		QString rmDir = QString(USER_DIR)+usrToDelete;
		if(!curDir.rmdir(rmDir))
		{
			LOG<<"Error! Cannot remove directory."<<endl;
			assert(0);
		}

		ui.usrNameEdit->clear();
		setAccountTable();

		if (DB.curUsr == usrToDelete)
		{
			OPT.hasLogined = false;
			mCurUser.clear();
		}
	}
}

void LoginDialog::dictMode()
{
	this->done(LT_Dictionary);
}
